<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const cai = {
        uname: '只因',
        age: 2.5,
        hobbit: ['sing', 'dance', 'rap', 'basketball'],
        fans: {
          uname: 'ikun',
          age: 9999,
          hobbit: ['smoke', 'drink', 'makeHairStyle'],
        },
      }
      const feng = {}

      function deepclone(newObj, oldObj) {
        for (let key in oldObj) {
          if (
            Object.prototype.toString.call(oldObj[key]) === '[object Array]'
          ) {
            newObj[key] = []

            deepclone(newObj[key], oldObj[key])
          } else if (
            Object.prototype.toString.call(oldObj[key]) === '[object Object]'
          ) {
            newObj[key] = {}

            deepclone(newObj[key], oldObj[key])
          } else {
            newObj[key] = oldObj[key]
          }
        }
      }

      deepclone(feng, cai)

      feng.fans.hobbit[2] = '我很棒，我喜欢写代码'

      console.log(feng)
      console.log(cai)

      //深拷贝：就是不断做浅拷贝的操作，直到所有的属性都是简单数据类型

      //准备一个空对象
      // const feng = {}

      function deepClone(newObj, oldObj) {
        //循环遍历需要被拷贝的对象
        for (let key in oldObj) {
          if (oldObj[key] instanceof Array) {
            //如果是数组
            //feng.hobbit:[] cai.hobbit:[........]
            //feng.fans.hobbit:[] cai.fans.hobbit:[......]
            //提前赋值
            newObj[key] = []
            // console.log(newObj[key], key)
            deepClone(newObj[key], oldObj[key])
          } else if (oldObj[key] instanceof Object) {
            //如果是对象
            //提前赋值
            newObj[key] = {}
            deepClone(newObj[key], oldObj[key])
          } else {
            //如果是简单数据类型，直接赋值
            //feng.hobbit[0] = cai.hobbit[0]
            //feng.hobbit[1] = cai.hobbit[1]
            //...
            //feng.fans.uname = cai.fans.uname
            //feng.fans.age = cai.fans.age
            //feng.fans.hobbit[0] = cai.fans.hobbit[0]
            //...
            newObj[key] = oldObj[key]
          }
        }
      }

      // deepClone(feng, cai)
      const feng = JSON.parse(JSON.stringify(cai))

      // feng.fans.hobbit[2] = '我很棒，我喜欢写代码'

      // console.log(feng)
      // console.log(cai)
    </script>
  </body>
</html>
